package com.demo.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    // 加上错误注解，如果是 SQLIntegrityConstraintViolationException 类型的报错就会进入该方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        // 根据 Duplicate entry 关键字判断是否为数据重复
        if(e.getMessage().contains("Duplicate entry")) {
            // 使用 split 将报错信息转为数组
            String[] split = e.getMessage().split(" ");
            // 截取重复的报错数据
            String msg = split[2] + "已存在";
            // 返回详细的错误信息
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 捕获自定义错误类型
     * @param e 错误类型对象
     * @return 消息实体
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e) {
        return R.error(e.getMessage());
    }
}
